package com.ahm.config;

import com.ahm.bean.User;
import com.ahm.bean.UserRole;
import com.ahm.mapper.PermissionMapper;
import com.ahm.mapper.UserMapper;
import com.ahm.mapper.UserRoleMapper;
import com.ahm.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/*功能描述
 * @author ahm
 */
@Service
public class LoginUserServiceImpl implements UserDetailsService {

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private PermissionMapper permissionMapper;

    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        System.out.println("-------------------"+username);
//
//        String encode = passwordEncoder.encode("admin");
        // 查询用户是否存在
        User user = userMapper.selectUserByName(username);

        if (user==null){
            System.out.println("该用户不存在");
            throw new UsernameNotFoundException("该用户不存在");
        }
        // 根据用户名查询到该用户
        // 设置密码
        String userPwd = user.getUserPwd();
        // 查询到用户的权限
        List<String> list = permissionMapper.selectVclValueByUserId(user.getId());
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i <list.size() ; i++) {
            if (i==list.size()-1){
                stringBuilder.append(list.get(i));
                break;
            }
            stringBuilder.append(list.get(i)+",");
        }
        String string = stringBuilder.toString();
        System.out.println("权限码为："+string);
//      AuthorityUtils.commaSeparatedStringToAuthorityList("admin")
        return new org.springframework.security.core.userdetails.User(username,userPwd,AuthorityUtils.commaSeparatedStringToAuthorityList(string));
    }
}
